<?php


namespace App\Services;


use App\Models\Admin;
use App\Models\UserRelation;
use Illuminate\Support\Facades\Http;

class UserService
{

    /**
     * 获取4级账号下的省代id
     *
     * @param int $user_type
     * @param int $user_id
     * @return array
     */
    public function getDistributions(int $user_type = 0, int $user_id = 0): array
    {
        if ($user_type === 0) {
            $user_type = session('admin.user_type');
        }
        if ($user_id === 0) {
            $user_id = session('admin.id');
        }

        if ($user_type != 4) {
            return [];
        }

        $user = UserRelation::where('user_id', $user_id)->select('belong_user_id')->get();

        if ($user->isEmpty()) {
            return [];
        }

        $user = $user->toArray();
        return array_column($user, 'belong_user_id') ?? [];
    }

    /**
     * 创建省代id
     *
     * @return string
     */
    public function createDistributorId(): string
    {
        $count = Admin::where('user_type', 2)->count();
        if (empty($count)) {
            return 'CN10001';
        }

        $uniqueId =  'CN' . (10000 + $count);
        $result = Admin::where('unique_id', $uniqueId)->first();
        if (!empty($result)) {
            return 'CN' . (10000 + $count + 1);
        }

        return $uniqueId;
    }

    /**
     * 通过省代id获取经销商账号数据
     *
     * @param array $idArr
     * @return array
     */
    public function getDealers(array $idArr)
    {
        $user = Admin::where('user_type', 3)->whereIn("creator_id", $idArr)->get();
        if (empty($user)) {
            return [];
        }

        $user = $user->toArray();
        return array_column($user, 'id') ?? [];
    }

    public function getBelongUserIdArr(int $userId)
    {
        $distributions = $this->getDistributions(4, $userId);
        $userIdArr = $distributions;
        if (!empty($distributions)) {
            $dealers = $this->getDealers($distributions);
            $userIdArr = array_merge($userIdArr, $dealers);
        }

        return $userIdArr ?? [];
    }

    public function countAllStores(string $startDate, string $endDate)
    {
        
    }

    public function createAccountId()
    {
        $count = Admin::whereNotIn('user_type', [2, 3])->count();
        if (empty($count)) {
            return 'AD000001';
        }

        $uniqueId = str_pad($count, 6, '0', STR_PAD_LEFT);
        $uniqueId =   'AD' . $uniqueId;
        $result = Admin::where('unique_id', $uniqueId)->first();
        if (!empty($result)) {
            return 'AD' . str_pad($count + 1, 6, '0', STR_PAD_LEFT);
        }

        return $uniqueId;
    }

    public function saveUserRelation(int $userId, array $distributions)
    {
        $relation = UserRelation::where('user_id', $userId)->first();
        if (!empty($relation)) {
            UserRelation::where('user_id', $userId)->delete();
        }
        $insertData = [];

        foreach ($distributions as $distribution) {
            $insertData[] = [
                'user_id'   => $userId,
                'belong_user_id'    => $distribution
            ];
        }

        return UserRelation::insert($insertData);
    }

    /**
     *
     *
     * @param string $mobile
     * @return false|mixed
     */
    public function getMobileArea(string $mobile)
    {
        if(!preg_match('/^1[345789]\d{9}$/ims', $mobile)) {
            return false;
        }

        $response = Http::get( 'https://way.jd.com/jisuapi/query4?appkey=191d18a440fb501de34699b8aa2bc500&shouji=' . $mobile );
        $result = $response->json();
        if ($result['code'] != 10000 || empty($result['result']) || empty($result['result']['result'])) {
            return false;
        }

        return $result['result']['result'];
    }
}